from typing import TypeVar, List, Union

from sqlalchemy import Select, func
from sqlalchemy.orm import Query, Session

T = TypeVar('T')


def paginate(query: Query[T], page: int, rows_per_page: int) -> tuple[Union[List[T], None], int]:
    total = query.count()
    results = query.offset(page).limit(rows_per_page).all()
    return results, total


def paginate_select(stmt: Select, page: int, rows_per_page: int, db: Session):
    total = db.query(func.count()).select_from(stmt.subquery()).scalar()
    results = db.execute(stmt.offset(page).limit(rows_per_page)).all()
    return results, total
